package com.stud.framework.web.service;

import com.stud.common.constant.CacheConstants;
import com.stud.common.exception.ServiceException;
import com.stud.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author Stud
 * @title XXXXX
 * @desription XXXXX
 * @data 2023-02-25 14:12
 */
@RequiredArgsConstructor
@Service
public class SerialNoService {
    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0000");
    private final RedissonClient redissonClient;
    private final RedisTemplate<String, String> redisTemplate;

    /**
     * @param businessCode 业务编码
     * @param total        生成编码数量
     * @return
     */
    public String[] create(String businessCode, int total) {

        if (total < 1) {
            throw new ServiceException("生成编码数量不能小于1");
        }

        if (StringUtils.isBlank(businessCode)) {
            throw new ServiceException("业务编码businessCode不能为空");
        }

        String formatDate = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        RAtomicLong atomicLong = redissonClient.getAtomicLong(CacheConstants.SERIAL_NO + businessCode + formatDate);
        atomicLong.expire(Duration.ofSeconds(86400));
        long num = atomicLong.addAndGet(total);

        String[] result = new String[total];
        for (int i = 0; i < total; i++) {
            result[i] = businessCode + formatDate + DECIMAL_FORMAT.format(num + i);
        }
        return result;
    }

    public String create(String businessCode) {
        return create(businessCode, 1)[0];
    }

}
